package cn.test.websocket;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.jws.Oneway;
import javax.websocket.Endpoint;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.web.socket.server.standard.SpringConfigurator;

//,configurator=SpringConfigurator.class可以实现注入
@ServerEndpoint(value = "/mywebsocket",configurator=SpringConfigurator.class)
public class DemoServlet {
	private static Map<String, Session> map = new HashMap<String, Session>();
	
	
	@OnMessage
	public void onMessage(String message, Session session) throws IOException,InterruptedException {

		// Print the client message for testing purposes
		System.out.println("Received: " + message);
		Iterator it = map.values().iterator();
		while (it.hasNext()) {
			Session tmp = (Session) it.next();
			tmp.getBasicRemote().sendText(session.getId() + ":" + message);
		}
	}
	
	@OnOpen
	public void onOpen(Session session) {
		map.put(session.getId(), session);
	}

	@OnClose
	public void onClose() {
		System.out.println("Connection closed");
	}
	
}
